<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Common\CommonController;
use App\Http\Controllers\Common\ArrayController;
use App\Model\AdminLog;
use App\Model\HomeLog;
use App\Model\Link;
use App\Model\Settings;
use App\Http\Requests\Admin\LinkRequest;
use Maatwebsite\Excel\Facades\Excel;

/**
 * 这是后台系统管理控制器
 * @author LiYongHeng <[616649679@qq.com]>
 * @date   2017-9-30
 */
class SystemController extends Controller
{
    /**
     * [__construct 中间件]
     */
    public function __construct()
    {
        // session中间件
        $this->middleware('adminSession');
        // 权限中间件
        $this->middleware('adminPower');
    }

    /**
     * [adminLogs 加载后台日志页面]
     * @return [object] [执行加载后台日志]
     */
    public function adminLogs(Request $request)
    {
        // 实例化公共函数文件
        $common = new CommonController;
        // 实例化公共数组文件
        $Array = new ArrayController;
        $type = $Array->adminLogType;
        //定义搜索数组
        $data = [];
        // 判断是否传入ip
        if ($request->input('ip') != '') {
            $data[] = ['IP', '=', $request->input('ip')];
        }
        // 判断是否传入类型
        if ($request->input('type') != '') {
            $data[] = ['type', '=', $request->input('type')];
        } 
        // 判断是否传入开始日期
        if ($request->input('startDate') != '') {
            $startTime = strtotime($request->input('startDate'));
            $data[] = ['addtime', '>=', $startTime];
        } 
        // 判断是否传入结束日期
        if ($request->input('endDate') != '') {
            $endTime = strtotime($request->input('endDate'));
            $data[] = ['addtime', '<', $endTime];
        }
        // 判断是否搜索内容
        if (!empty($data)) {
            //查询搜索的结果
            $result = AdminLog::where($data)->select('username', 'type','IP', 'addtime', 'content')->orderBy('id', 'desc')->paginate(5);
        } else {
            //查询所有的结果
            $result = AdminLog::select('username', 'type','IP', 'addtime', 'content')->orderBy('id', 'desc')->paginate(5);
        }
     
        return view('/Admin/System/adminLogs', [
            'result' => $result,
            'type' => $type,
            'ip' => $request->input('ip'),
            'ty' => $request->input('type'),
            'startDate' => $request->input('startDate'),
            'endDate' => $request->input('endDate'),
            ]);
    }

    /**
     * [homeLogs 加载前台日志有页面]
     * @return [object] [执行加载前台日志有页面]
     */
    public function homeLogs(Request $request)
    {
        // 实例化公共函数文件
        $common = new CommonController;
        // 实例化公共数组文件
        $Array = new ArrayController;
        $type = $Array->homeLogType;
        // 定义搜索数组
        $data = [];
        // 判断是否传入ip
        if ($request->input('ip') != '') {
            $data[] = ['IP', '=', $request->input('ip')];
        }
        // 判断是否传入类型
        if ($request->input('type') != '') {
            $data[] = ['type', '=', $request->input('type')];
        } 
        // 判断是否传入开始日期
        if ($request->input('startDate') != '') {
            $startTime = strtotime($request->input('startDate'));
            $data[] = ['addtime', '>=', $startTime];
        } 
        // 判断是否传入结束日期
        if ($request->input('endDate') != '') {
            $endTime = strtotime($request->input('endDate'));
            $data[] = ['addtime', '<', $endTime];
        }
         if (!empty($data)) {
            // 查询搜索的结果
            $result = HomeLog::where($data)->select('username', 'type','IP', 'addtime', 'content')->orderBy('id', 'desc')->paginate(5);
        } else {
            // 查询所有的结果
            $result = HomeLog::select('username', 'type','IP', 'addtime', 'content')->orderBy('id', 'desc')->paginate(5);
        }

        return view('/Admin/System/homeLogs', [
            'result' => $result,
            'type' => $type,
            'ip' => $request->input('ip'),
            'ty' => $request->input('type'),
            'startDate' => $request->input('startDate'),
            'endDate' => $request->input('endDate'),
            ]);
    }

    /**
     * [settings 加载系统设置页面]
     * @return object [执行加载]
     */
    public function settings()
    {
        // 实例化公共函数文件
        $common = new CommonController;
        // 查询系统设置数据
        $result = Settings::first();
        //下载图片并赋值
        $homeLogo =  $common->downloadFile( $result->home_logo);
        $adminLogo =  $common->downloadFile( $result->admin_logo);
        $pic1 =  $common->downloadFile( $result->pic1);
        $pic2 =  $common->downloadFile( $result->pic2);
        $pic3 =  $common->downloadFile( $result->pic3);
        $pic4 =  $common->downloadFile( $result->pic4);
        $pic5 =  $common->downloadFile( $result->pic5);

        return view('/Admin/System/settings', [
            'result' => $result, 
            'homeLogo' => $homeLogo,
            'adminLogo' => $adminLogo,
            'pic1' => $pic1,
            'pic2' => $pic2,
            'pic3' => $pic3,
            'pic4' => $pic4,
            'pic5' => $pic5,
            ]);
    }

    /**
     * [saveSettings 保存系统设置]
     * @param  Request $request [请求数据]
     * @return object           [返回成功或失败信息并重定向]
     */
    public function saveSettings(Request $request)
    {
        // 实例化公共函数文件
        $common = new CommonController;
        // 查询系统设置数据
        $settings = Settings::first();
        // 赋值传入数据
        $homeTitle = $request->input('homeTitle');
        $registerCode = $request->input('registerCode');
        $adminCode = $request->input('adminCode');
        $homeLogo = $request->input('homeLogo');

        //判断是否有上传前台Logo图片
        $res = $common->uploadToQiNiu($request, 'homeLogo');
        if ($res) {
            $home_logo = $res['key'];
        } else {
            $home_logo = $settings->home_logo;
        }
        // 判断是否有上传后台Logo图片
        $res = $common->uploadToQiNiu($request, 'adminLogo');
        if ($res) {
             $admin_logo = $res['key'];
        } else {
            $admin_logo = $settings->admin_logo;
        }
        //判断是否上传轮播图一
        $res = $common->uploadToQiNiu($request, 'pic1');
        if ($res) {
            $pic1 = $res['key'];
        } else {
            $pic1 = $settings->pic1;
        }
        // 判断是否上传轮播图二
        $res = $common->uploadToQiNiu($request, 'pic2');
       if ($res) {
            $pic2 = $res['key'];
        } else {
            $pic2 = $settings->pic2;
        }
        // 判断是否上传轮播图三
        $res = $common->uploadToQiNiu($request, 'pic3');
        if ($res) {
            $pic3 = $res['key'];
        } else {
            $pic3 = $settings->pic3;
        }
        // 判断是否上传轮播图四
        $res = $common->uploadToQiNiu($request, 'pic4');
       if ($res) {
            $pic4 = $res['key'];
        } else {
            $pic4 = $settings->pic4;
        }
        // 判断是否上传轮播图五
        $res = $common->uploadToQiNiu($request, 'pic5');
        if ($res) {
            $pic5 = $res['key'];
        } else {
            $pic5 = $settings->pic5;
        }

        $result = Settings::where('id', 1)->update([
            'home_logo' => $home_logo,
            'admin_logo' => $admin_logo,
            'pic1' => $pic1,
            'pic2' => $pic2,
            'pic3' => $pic3,
            'pic4' => $pic4,
            'pic5' => $pic5,
            'shop_title' => $homeTitle,
            'registerCode' => $registerCode,
            'adminCode' => $adminCode,
            ]);
        // 判断是否修改成功
        if ($result) {
            // 记录操作到后台日志
            $common->admin_log(session('adminUser')['username'], 9, "修改系统设置");
            return redirect('/admin/System/settings')->with('content','保存成功');
        } else {        
            return redirect('/admin/System/settings')->with('content','保存失败');
        }
    }

    /**
     * [excel 导出Excel功能]
     * @return void
     */
    public function excel()
    {
        //查询要导出的数据表的字段，注意不要使用*符合查询所有字段
        $content = AdminLog::select('username','content', 'IP', 'addtime')->orderBy('id', 'desc')->get();
        //转换为数组格式
        $result = $content->toArray();
        Excel::create("Excel文档", function($excel) use($result)
        {
            //创建sheet
            $excel->sheet('sheet1',function($sheet)  use($result)
            {
                    //填充每个单元格的内容
                    $sheet->row(1,array('序号','用户名','操作内容','操作时间'));
                    $sheet->setWidth('A', 10);
                    $j = 2;
                    foreach ($result as $k => $v) {
                        $sheet->row($j,array($k+1,$v['username'], $v['content'], $v['IP'],date('Y-m-d H:i:s',$v['addtime'])));
                        $j++;
                    }                    

            });
        })->export('xls');

    }

    /**
     * [link 友情链接]
     * @return [object] [执行加载模板]
     */
    public function link()
    {
        //查询所有链接信息
        $result = Link::select('id', 'title', 'url')->get();
        return view('/Admin/System/link', ['result' => $result]);
    }

    /**
     * [createLink 加载添加友情链接页面]
     * @return [object] [执行加载]
     */
    public function createLink()
    {
        return view('/Admin/System/createLink');
    }

    /**
     * [addLink 添加友情链接]
     * @param LinkRequest $request [验证传入数据]
     * @return json 返回json格式状态码与信息
     */
    public function addLink(LinkRequest $request)
    {
        // 实例化公共函数文件
        $common = new CommonController;
        // 赋值传入数据
        $url = $request->input('url');
        $title = $request->input('title');
        // 执行添加
        $res = Link::insertGetId([
                'title' => trim($title),
                'url' => trim($url),
            ]);
        // 判断是否添加成功
        if ($res>0) {
            // 记录操作到后台日志
            $common->admin_log(session('adminUser')['username'], 12, "添加链接:".trim($url));
            return $common->json(2000, '添加成功');
        } else {
            return $common->json(1450, '添加失败');
        }
    }

    /**
     * [editLink 加载修改链接页面]
     * @param  [int]  $id      [传入id]
     * @return [object]           [执行加载]
     */
    public function editLink($id)
    {
        // 查询当前传入id的链接信息
        $result = Link::where('id', $id)->select('id', 'title', 'url')->first();
        return view('/Admin/System/editLink', ['result' => $result]);
    }

    /**
     * [updateLink 修改链接]
     * @param  LinkRequest $request [验证传入数据]
     * @return [json]              返回json格式状态码与信息
     */
    public function updateLink(LinkRequest $request) 
    {
        // 实例化公共函数文件
        $common = new CommonController;
        // 赋值传入数据
        $url = $request->input('url');
        $title = $request->input('title');
        $id = $request->input('id');
        // 执行修改
        $res = Link::where('id', $id)->update([
                'title' => trim($title),
                'url' => trim($url),
            ]);
        // 判断是否修改成功
        if ($res>0) {
            // 记录操作到后台日志
            $common->admin_log(session('adminUser')['username'], 13, "修改链接:".trim($url));
            return $common->json(2000, '修改成功');
        } else {
            return $common->json(1450, '修改失败');
        }
    }
    /**
     * [delLink 删除链接]
     * @param  [int] $id [删除的id]
     * @return [object]     [返回重定向跳转]
     */
    public  function delLink($id)
    {
        // 实例化公共函数文件
        $common = new CommonController;
        // 执行删除
        $res = Link::where('id', $id)->delete();
        // 判断是否删除成功
        if ($res) {
            // 记录操作到后台日志
            $common->admin_log(session('adminUser')['username'], 14, "删除链接");
             return redirect('/admin/System/link')->with('content','删除成功');
        } else {
             return redirect('/admin/System/link')->with('content','删除失败');
        }
    }
}
